package com.doctor.controller;

import java.io.IOException;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.doctor.utils.OSSClientUtil;
import com.doctor.utils.QiNiuUtils;

@Controller
public class UploadController extends BaseController{
	
	@Resource
    private OSSClientUtil ossClient;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
    /**
     * oss单附件图片上传
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload/image")
    @ResponseBody
    public JSONObject imgUpload(@RequestParam("file") MultipartFile file) {
    	JSONObject obj = new JSONObject();
        String imgUrl = null;
        try {
            if (file == null || file.getSize() <= 0) {
                throw new Exception("图像不能为空");
            }
            String name = ossClient.uploadImg2Oss(file);
			
			obj.put("code", "0");
			obj.put("msg", "上传成功");
			
			JSONObject o = new JSONObject();
			o.put("src", name);
			o.put("title",file.getOriginalFilename());
			obj.put("data", o);
        } catch (Exception e) {
			obj.put("code", "-1");
			obj.put("msg", "上传失败");
			
			JSONObject o = new JSONObject();
			o.put("src", "");
			o.put("title",e.getMessage());
			obj.put("data", o);
        }
        return obj;
    }
	
	/**
	 * 七牛
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/upload/image_old")
	public JSONObject upload(@RequestParam MultipartFile file) throws IOException{
		JSONObject obj = new JSONObject();
		try {
			
			QiNiuUtils  util =new QiNiuUtils();
			String url = util.upload(file);
			
			logger.debug(url);
			
			obj.put("code", "0");
			obj.put("msg", "上传成功");
			
			JSONObject o = new JSONObject();
			o.put("src", url);
			o.put("title",file.getOriginalFilename());
			obj.put("data", o);
			
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("code", "-1");
			obj.put("msg", "上传失败");
			
			JSONObject o = new JSONObject();
			o.put("src", "");
			o.put("title",e.getMessage());
			obj.put("data", o);
		}
		
		return obj;
	}
	

}
